package com.cw.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cw.common.method.SendCardMsg;
import com.cw.entity.*;
import com.cw.mapper2.*;
import com.cw.util.MQMsg;
import com.cw.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Component
@EnableAsync
public class MassageTask<M extends BaseMapper<PatientBedMiddleRjbf>> {
    @Autowired
    protected M baseMapper;

    @Autowired
    private ThisIiPrepayinMapper thisIiPrepayinMapper;

    @Autowired
    private PatientBedMiddleRjszMapper  patientBedMiddleRjszMapper;

    @Autowired
    private REmployeeMapper rEmployeeMapper;

    @Autowired
    private WeChatLogMapper weChatLogMapper;

    @Autowired
    private TelMessageMapper telMessageMapper;

    private MQMsg mqMsg = new MQMsg();

    @Autowired
    private MqLogMapper mqLogMapper;

    @Autowired
    private RjbfCenterMapper rjbfCenterMapper;

    /**
     * 每天8点定时查询
     * @return
     */
    @Scheduled(cron = "0 0 8 * * ?")
    public void sendPatientMassage(){
        // 查询数据库  查询状态为已经预约的
        List<PatientBedMiddleRjbf> patientBed = baseMapper.selectList(new LambdaQueryWrapper<>(new PatientBedMiddleRjbf())
                .eq(PatientBedMiddleRjbf::getState, "1"));
        // 比较预约时间-当前时间相差<=3
        // 发送短信给患者
        Date date = new Date();
        // 日期相减的时候不包含头尾两天，所以3-1=2
        List<PatientBedMiddleRjbf> appointList = patientBed.stream().filter(p ->
                TimeUnit.DAYS.convert(p.getAppointmentTime().getTime() - date.getTime(),TimeUnit.MILLISECONDS) == 2).collect(Collectors.toList());
        if (appointList.size() != 0){
            // 发送短信给患者
            List<ThisIiPrepayin> patientList =  thisIiPrepayinMapper.selectByIdList(appointList);
            getMsgInfo(patientList,1,1);
        }

        // 预约时间-当前时间相差<=1
        List<PatientBedMiddleRjbf> docWechatList = patientBed.stream().filter(p ->
                TimeUnit.DAYS.convert(p.getAppointmentTime().getTime() - date.getTime(),TimeUnit.MILLISECONDS) == 0).collect(Collectors.toList());
        if (docWechatList.size() != 0){
            // 发送企业微信到医生
            List<ThisIiPrepayin> doclist =  thisIiPrepayinMapper.selectByIdList(docWechatList);
            getMsgInfo(doclist,1,2);
        }

    }

    private void getMsgInfo(List<ThisIiPrepayin> sendList, int flag, int sendFlag) {
        for (ThisIiPrepayin patientInfo: sendList) {
            MsgInfo info = new MsgInfo();
            info.setName(patientInfo.getName());
            // 根据查询到preid去表中查
            PatientBedMiddleRjbf entity = patientBedMiddleRjszMapper.selectByPreid(Long.parseLong(patientInfo.getPreid().toString()));

            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
            String date = ft.format(entity.getAppointmentTime());
            info.setAppointMentDate(date);
            info.setAppointmentTime(entity.getAppointmentClasses());
            info.setLinkmanTel(patientInfo.getHomeTel());
            info.setPreid(patientInfo.getPreid());
            // 企业微信编号
            LambdaQueryWrapper<REmployee> lambdaQueryEmployeeWrapper = new LambdaQueryWrapper<>();
            lambdaQueryEmployeeWrapper.eq(REmployee::getEmplCode, patientInfo.getPredoctCode());
            REmployee retREmployee = rEmployeeMapper.selectOne(lambdaQueryEmployeeWrapper);
            // 测试使用
//            info.setWechatAccountCode("102690");
            if (retREmployee != null) {
                info.setWechatAccountCode(retREmployee.getXgzh());
            }

            if (flag == 0) {
                info.setTitle("日间病房床位取消预约成功");
                info.setResult("已取消");
            } else {
                info.setTitle("日间病房床位预约成功");
                info.setResult("已预约");
            }
            setMsg(info);
            switch (sendFlag){
                // 发送病人
                case 1:
                    if (entity.getPatientSendFlag()!=null && entity.getPatientSendFlag() == 1){
                        break;
                    }
                    new Thread(()->{
                        try{
                            //调用医院发送手机短信的接口
                            TelMessageLog telMessageLog = SendCardMsg.sendTelMessage2(info, mqMsg.getMsgContent(),0);
                            telMessageMapper.insert(telMessageLog);
                            rjbfCenterMapper.updatePatientSendFlag(Long.parseLong(info.getPreid().toString()));
                        } catch (Exception ex){
                            ex.printStackTrace();
                        }
                    }).start();
                    break;
                // 发送医生
                case 2:
                    if (entity.getDocSendFlag() != null && entity.getDocSendFlag() == 1){
                        break;
                    }
                    new Thread(()->{
                        try{
                            //发送企业微信
                            if (info.getWechatAccountCode()!=null && !info.getWechatAccountCode().isEmpty()) {
                                //企业微信返回josn消息体
                                //调用post发送企业微信消息
                                WeChatLog weChatLog = SendCardMsg.send3(info,entity);
                                weChatLogMapper.insert(weChatLog);
                            }
                            rjbfCenterMapper.updateDocSendFlag(Long.parseLong(info.getPreid().toString()));
                        } catch (Exception ex){
                            ex.printStackTrace();
                        }
                    }).start();
                    break;
                default:
                    break;
            }


        }
    }

    public void setMsg(MsgInfo msgInfo){
        // 预约表根据病人id查询，如果存在就发送信息
        PatientBedMiddleRjbf appointmentMsg = patientBedMiddleRjszMapper.selectByPreid(Long.parseLong(msgInfo.getPreid().toString()));

        if (appointmentMsg != null){
            // 设定用户
            mqMsg.setUserName("S01");
            // 设定密码
            mqMsg.setPassword("123456");
            // 设定通道池
            mqMsg.setQueueManagerName("QMGR.P01");
            // 设定消息频道
            mqMsg.setChannel("PS35035");
            // 设定姓名
            mqMsg.setPatName(msgInfo.getName());
            // 索引号
            mqMsg.setPatIndexNo(msgInfo.getPreid().toString());
            mqMsg.setMsgTitle(msgInfo.getTitle());
            // 医生姓名工号
            mqMsg.setReciveCode(appointmentMsg.getDocCode());
            mqMsg.setReciveName(appointmentMsg.getDocName());
            // 预约时间
            Date appointmentTime = appointmentMsg.getAppointmentTime();
            // 获取年  月  日
            ZoneId timeZone = ZoneId.systemDefault();
            LocalDate getDate = appointmentTime.toInstant().atZone(timeZone).toLocalDate();
            // 年
            int year = getDate.getYear();
            // 月
            int month = getDate.getMonthValue();
            // 日
            int day = getDate.getDayOfMonth();

            //发给个人
            mqMsg.setMessageType("2");
            mqMsg.setMsgContent(msgInfo.getName() + "先生/女士"+year+"年"+month+"月"+day+"日是您预约来我院治疗的日子，请您于" + year+"年"+month+"月"+day+"日"+"携带好您的医保卡、身份证、空腹至苏州大学附属第二医院三香路院区二号楼2楼日间治疗中心办理入院治疗。如有特殊情况请联系您的主治医师或咨询电话：0512-67784215，迟到者需重新预约。感谢您的理解与配合！");
            mqMsg.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

            // 设定发送者工号
            mqMsg.setSenderCode(msgInfo.getEmplCode());
            // 设定发送者姓名
            mqMsg.setSenderName(msgInfo.getEmplName());
            // 设定床位号
            mqMsg.setBedNum(msgInfo.getBedNum());
            // 设定科室编号
            mqMsg.setDeptCode(msgInfo.getDeptCode());
            // 设定科室名称
            mqMsg.setDeptName(msgInfo.getDeptName());
            // 病区代码
            mqMsg.setWardCode(msgInfo.getNurseCellCode());
            // 设定病区名称
            mqMsg.setWardName(msgInfo.getNurseCellName());
            // 设定院区编号
            mqMsg.setHospDistrictCode(msgInfo.getYard());
            // 设定院区
            mqMsg.setHostDistrictName(msgInfo.getYardName());
            mqMsg.setReciveCode(appointmentMsg.getDocCode());
            mqMsg.setReciveName(appointmentMsg.getDocName());
            String xmlString = mqMsg.createXMLString(mqMsg);

            MqLog mqLog = new MqLog();
            String uuid = UUIDUtil.uuid();
            mqLog.setId(uuid);
            mqLog.setRequestMsg(xmlString);
            mqLog.setRequestDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            mqLog.setSenderCode(msgInfo.getEmplCode());
            mqLog.setSenderName(msgInfo.getEmplName());

            String msgId = mqMsg.putMsg(xmlString);
            System.out.println(msgId);
            mqLog.setMsgId(msgId);
            if (msgId != "") {
                mqLog.setResponseType("success");
            } else {
                mqLog.setResponseType("fail");
            }
            mqLogMapper.insert(mqLog);
        }
    }
}
